package com.yinhai.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.cmcc.groupcontacts.MainApp;
import com.listener.MsgTextLongClickListener;
import com.littlec.sdk.entity.CMGroup;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.listener.CMGroupListener;
import com.littlec.sdk.manager.CMGroupManager;
import com.littlec.sdk.manager.CMIMHelper;
import com.littlec.sdk.utils.CMChatListener;
import com.yinhai.asynctask.BaseTask;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.model.MsgModel;
import com.yinhai.service.MsgServiceImpl;
import com.yinhai.util.NullUtils;
import com.yinhai.util.PhoneNameMapUtil;
import com.yinhai.util.Util;

/**
 * 群组
 * 
 * @author lixh
 * 
 */
public class ChatGroupActivity extends Activity {
    private ListView listView;
    
    private SimpleAdapter adapter;
    
    private List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
    
    private String sendUserId;
    
    private Context context;
    
    private MsgServiceImpl msgServiceImpl;
    
    MsgModel resendMsgModel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_group);
        msgServiceImpl = new MsgServiceImpl(this);
        if (getIntent().hasExtra(MsgTextLongClickListener.SER_KEY)) {
            resendMsgModel = (MsgModel)getIntent().getSerializableExtra(MsgTextLongClickListener.SER_KEY);
        }
        listView = (ListView)findViewById(R.id.group_list);
        context = ChatGroupActivity.this;
        
        sendUserId = LoginConfigUtil.getConfig(this).getImUserName();
        adapter =
            new SimpleAdapter(this, datas, R.layout.chat_group_item_new, new String[] {"name", "username"}, new int[] {
                R.id.title, R.id.title_user});
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Map<String, Object> item = datas.get(arg2);
                Intent intent = new Intent(ChatGroupActivity.this, ChatActivity.class);
                
                intent.putExtra("sendID", sendUserId);
                intent.putExtra("sendName", PhoneNameMapUtil.findName(sendUserId, context));
                intent.putExtra("receID", item.get("id") == null ? "" : item.get("id").toString());
                intent.putExtra("receName", item.get("name") == null ? "" : item.get("name").toString());
                intent.putExtra("type", 3);// 1:一对一；2：部门；3：群组
                intent.putExtra("groupId", item.get("id").toString());
                intent.putExtra("groupName", item.get("name") == null ? "" : item.get("name").toString());
                if (resendMsgModel != null) {
                    intent.putExtra(MsgTextLongClickListener.SER_KEY, resendMsgModel);
                }
                startActivity(intent);
                finish();
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Map<String, Object> item = datas.get(arg2);
                final CMGroup group = (CMGroup)item.get("data");
                List<CMMember> cmMembers = CMIMHelper.getCmGroupManager().getGroupMembersfromServer(group.getGroupId());
                // 判断当前讨论组是否是当前登录用户添加
                if (NullUtils.isNotEmpty(cmMembers) && sendUserId.equals(cmMembers.get(0).getMemberId())) {
                    new AlertDialog.Builder(ChatGroupActivity.this).setTitle("操作选择")
                        .setItems(new String[] {"查看群组", "修改群组", "删除群组"}, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        doDetailGroup(group);
                                        break;
                                    // 修改群组
                                    case 1:
                                        doModifyGroup(group);
                                        break;
                                    // 删除群组
                                    case 2:
                                    	doDeleteGroup(group);
//                                    case 3:
//                                        exitGroup(group);
                                    default:
                                        break;
                                }
                            }
                        })
                        .show();
                } else {
                    new AlertDialog.Builder(ChatGroupActivity.this).setTitle("操作选择")
                        .setItems(new String[] {"查看群组", "退出群组"}, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        doDetailGroup(group);
                                        break;
                                    case 1:
                                        exitGroup(group);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                        .show();
                }
                return true;
            }
            
        });
        
    }
    
    public void onResume() {
        super.onResume();
        if (MainApp.isIMConnecteStatus != 2) {
            Util.showMsg(this, "请重新登录即时通讯");
            return;
        }
        datas.clear();
        adapter.notifyDataSetChanged();
        CMIMHelper.getCmGroupManager().getGroupListFromServer(new CMChatListener.OnGroupListener() {
            
            @Override
            public void onSuccess(List<CMGroup> groups) {
                for (CMGroup group : groups) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", group.getGroupId());
                    map.put("name", group.getGroupName());
                    map.put("data", group);
                    datas.add(map);
                }
                adapter.notifyDataSetChanged();
            }
            
            @Override
            public void onFailed(String arg0) {
                Util.showMsg(ChatGroupActivity.this, "         ");
            }
        });
    }
    
    // 返回
    public void doBack(View view) {
        onBackPressed();
    }
    
    public void doModifyGroup(CMGroup cmGroup) {
        Intent intent = new Intent(this, ChatAddGroupActivity.class);
        intent.putExtra("groupID", cmGroup.getGroupId());
        startActivityForResult(intent, 123456);
    }
    
    public void doDetailGroup(CMGroup group) {
        Intent intent = new Intent(this, ChatDetailGroupActivity.class);
        intent.putExtra("groupID", group.getGroupId());
        intent.putExtra("groupName", group.getGroupName());
        this.startActivity(intent);
    }
    
    // 添加群组
    public void doAddGroup(View view) {
        Intent intent = new Intent(this, ChatAddGroupActivity.class);
        intent.putExtra("groupId", "");
        startActivityForResult(intent, 123456);
    }
    
    /**
     * 删除群组
     * 
     * @param groupId
     */
    public void doDeleteGroup(final CMGroup group) {
        // // 获取当前分组下面的所有成员电话号码进行发送短消息
        // List<IMUserGroup> phoneList =
        // imUserGroupService.findByGroupId(groupId);
        // DeleteGroupTask deleteGroupTask = new DeleteGroupTask(context, datas,
        // adapter, phoneList, sendUserId, "", groupId);
        // List<NameValuePair> postParam = new ArrayList<NameValuePair>();
        // NameValueParam groupIdp = new NameValueParam();
        // groupIdp.setName("group_id");
        // groupIdp.setValue(groupId);
        // postParam.add(groupIdp);
        // AsyncTaskParam deleteGroup = new AsyncTaskParam(UrlConstant.LOCAL_URI
        // + UrlConstant.DELETE_GROUP);
        // deleteGroup.setPostParam(postParam);
        // deleteGroupTask.execute(deleteGroup);
    	  AlertDialog.Builder adg = new AlertDialog.Builder(ChatGroupActivity.this);
          adg.setTitle("删除群组:");
          adg.setMessage("是否删除群组？");
          adg.setPositiveButton("确定", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                  new BaseTask<String, String, String>(ChatGroupActivity.this, "正在执行退群操作，请稍等......") {
                      
                      @Override
                      protected void onSuccess(String result) {
                         
                          Util.showMsg(context, "退群成功");
                      }
                      
                      @Override
                      protected String doInBack(String... params)
                          throws Exception {
//                          CMIMHelper.getCmGroupManager().exitGroup(params[0]);
                    	  CMGroupManager.getInstance().deleteGroup(group.getGroupId(), new CMGroupListener.OnAddGroupListener(){

							@Override
							public void onSuccess(List<CMMember> members,
									String groupId) {
									  msgServiceImpl.delIMListByGroup(LoginConfigUtil.getConfig(ChatGroupActivity.this).getUsername(),
			                              group.getGroupId());
			                          sendBroadcast(new Intent("com.im.message"));
							}

							@Override
							public void onFailed(String groupId) {
								 Util.showMsg(context, "操作失败!");
							}
                    		  
                    	  });
                          return "";
                      }
                      
                      @Override
                      protected void onError() {
                          Util.showMsg(context, "操作失败，请稍后重试");
                      }
                      
                  }.execute(group.getGroupId());
              }
          });
          adg.setNegativeButton("取消", null);
          adg.show();
    }
    
    private void exitGroup(final CMGroup group) {
        AlertDialog.Builder adg = new AlertDialog.Builder(ChatGroupActivity.this);
        adg.setTitle("退出群组:");
        adg.setMessage("是否退出群组？");
        adg.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                new BaseTask<String, String, String>(ChatGroupActivity.this, "正在执行退群操作，请稍等......") {
                    
                    @Override
                    protected void onSuccess(String result) {
                        for (Map<String, Object> map : datas) {
                            if (map.get("id").toString().equals(group.getGroupId())) {
                                datas.remove(map);
                                adapter.notifyDataSetChanged();
                                break;
                            }
                        }
                        
                        Util.showMsg(context, "退群成功");
                        
                        msgServiceImpl.delIMListByGroup(LoginConfigUtil.getConfig(ChatGroupActivity.this).getUsername(),
                            group.getGroupId());
                        sendBroadcast(new Intent("com.im.message"));
                    }
                    
                    @Override
                    protected String doInBack(String... params)
                        throws Exception {
//                        CMIMHelper.getCmGroupManager().exitGroup(params[0]);
                        return "";
                    }
                    
                    @Override
                    protected void onError() {
                        Util.showMsg(context, "操作失败，请稍后重试");
                    }
                    
                }.execute(group.getGroupId());
            }
        });
        adg.setNegativeButton("取消", null);
        adg.show();
        
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123456 && resultCode == RESULT_OK) {
            // // TODO群组有更新 ，重新取数据
            // String groupId = data.getExtras().getString("groupId", "");
            // String groupName = data.getExtras().getString("groupName", "");
            // boolean flag = false;
            // Map<String, String> map = null;
            // for (int i = 0; i < datas.size(); i++) {
            // map = datas.get(i);
            // if (map.get("id").equals(groupId)) {
            // flag = true;
            // map.put("name", groupName);
            // }
            // }
            // if (!flag) {
            // map = new HashMap<String, String>();
            // map.put("name", groupName);
            // map.put("id", groupId);
            // map.put("user_phone", sendUserId);
            // datas.add(map);
            // }
            // adapter.notifyDataSetChanged();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
